package com.didispace.web;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


@Service
public class HelloService {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    Hello helloService;

    @HystrixCommand(fallbackMethod = "helloFallback", commandKey = "helloKey")
    public String hello(String blog) {
        long start = System.currentTimeMillis();

        StringBuilder result = new StringBuilder();
        //  RestTemplate 和 Feign 任选其一
        //  result.append(restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class).getBody());
        //  hello方法 用线程睡眠模拟了超时
        result.append(helloService.hello()).append("\t");
        result.append(helloService.vnshu(blog));

        long end = System.currentTimeMillis();
        logger.info("Spend time : " + (end - start));
        return result.toString();
    }

    /**
     * HystrixCommand 指定的回调函数，值得注意的是，它们的参数列表须保持一致
     *
     * @param blog
     * @return
     */
    public String helloFallback(String blog) {
        return "request failed because of timeout, param: blog\t" + blog;
    }

}